﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.DataAccess;
using MShop.Core.Domain;
using MShop.Core.Service.Membership;
using MShop.Core.Extensions;

namespace MShop.Web.Areas.Admin.Controllers
{
    public class DiscountController : SecureController
    {
        private readonly ICommonDao<Discount> _CommonDao;
        private readonly IRoleService  _Roles;  
        public DiscountController(ICommonDao<Discount> commonDao,IRoleService roles)
        {
            _Roles = roles;
            _CommonDao = commonDao;
            _CommonDao.PrimaryKey = "RoleId";
        }
        
        public ActionResult Index()
        {
            return View(_CommonDao.GetAll());
        }


        public ActionResult Edit(Guid? id)
        {

            if (id.HasValue)
            {
                var m=_CommonDao.GetById(id.Value);

                ViewData["roles"] = _Roles.FindRoles().ConvertListItem("RoleName", "RoleId", m.RoleId);
                return View(m);
            }

            ViewData["roles"] = _Roles.FindRoles().ConvertListItem("RoleName", "RoleId");

            return View(new Discount());
        }


        public ActionResult Delete(int id)
        {
            var discount = _CommonDao.GetById(id);
            _CommonDao.Delete(discount);
            _CommonDao.SaveChanges();
            return RedirectToAction("index");
        }


        [HttpPost]
        public ActionResult Edit(Guid?id, Discount discount)
        {


            if (id.HasValue)
            {
                var m = _CommonDao.GetById(id.Value);



                if (ModelState.IsValid)
                {
                    var db = _CommonDao.GetById(id);
                    UpdateModel<Discount>(db, new string[] { "RoleId", "Icon", "Point", "DiscountDot" });
                    _CommonDao.SaveChanges();
                    return RedirectToAction("index");
                }

               
            }
            else
            {

                if (ModelState.IsValid)
                {
                    _CommonDao.Save(discount);
                    _CommonDao.SaveChanges();
                    return RedirectToAction("index");
                }
            }

            ViewData["roles"] = _Roles.FindRoles().ConvertListItem("RoleName", "RoleId", discount.RoleId);         

            return View(discount);

            
        }
    }
}
